package com.cct.digitalarchapi.service.impl;

import com.cct.digitalarchapi.common.Response;
import com.cct.digitalarchapi.dao.*;
import com.cct.digitalarchapi.pojo.Menu;
import com.cct.digitalarchapi.pojo.Role;
import com.cct.digitalarchapi.pojo.dto.MenuDto;
import com.cct.digitalarchapi.pojo.dto.RoleMenuDto;
import com.cct.digitalarchapi.pojo.vo.AllMenuVo;
import com.cct.digitalarchapi.pojo.vo.AllRoleMenuVo;
import com.cct.digitalarchapi.pojo.vo.RoleMenuVo;
import com.cct.digitalarchapi.service.RoleAndMenuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @FileName RoleAndMenuServiceImpl
 * @Description 实现类
 * @Author Created by chenmingzhe
 * @Date 2023/11/19
 **/
@Slf4j
@Service
public class RoleAndMenuServiceImpl implements RoleAndMenuService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private StaffListMapper staffListMapper;
    @Autowired
    private RootListMapper rootListMapper;

    @Override
    public Response addRole(String roleName, List<Integer> menuList) {
        try {
            String num=roleMapper.qryHaveRole(roleName);
            if("0".equals(num)){
                Role role=new Role();
                role.setRoleName(roleName);
                roleMapper.addRole(role);
                int roleId=role.getRoleId();
                for (Integer menuId : menuList) {
                    if("0".equals(roleMenuMapper.qryHaveMenu(roleId,menuId))){
                        roleMenuMapper.addRoleMenu(roleId,menuId);
                    }
                }
            }else{
                return Response.bad("该角色已存在");
            }
            return Response.success("");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("新增角色失败：{}", e.getMessage());
            return Response.error("新增角色失败");
        }
    }

    @Override
    public Response updateRole(int roleId, String roleName, List<Integer> menuList) {
        try {
            roleMapper.updateRole(roleId,roleName);
            roleMenuMapper.deleteRoleMenu(roleId);
            Map<Integer,Integer> map =new HashMap<>();
            for (Integer menuId : menuList) {
                Menu menu=menuMapper.getMenuById(menuId);
                if(menu.getParentId()!=0){
                    if(!map.containsKey(menu.getParentId())){
                        map.put(menu.getParentId(),menu.getParentId());
                    }
                }
                roleMenuMapper.addRoleMenu(roleId,menuId);
            }
            for (Integer menuId : map.keySet()) {
                if("0".equals(roleMenuMapper.qryHaveMenu(roleId,menuId))) {
                    roleMenuMapper.addRoleMenu(roleId, menuId);
                }
            }
            return Response.success("");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("修改角色名失败：{}", e.getMessage());
            return Response.error("修改角色名失败");
        }
    }
    @Override
    public Response deleteRole(int roleId) {
        try {
            String num=staffListMapper.qryHaveRoleUser(roleId);
            String num2=rootListMapper.qryHaveRoleUser(roleId);
            if("0".equals(num)&&"0".equals(num2)) {
                roleMapper.deleteRole(roleId);
                roleMenuMapper.deleteRoleMenu(roleId);
                return Response.success("");
            }else {
                return Response.bad("您暂时不能删除该角色，还有属于该角色的员工");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除角色失败：{}", e.getMessage());
            return Response.error("删除角色失败");
        }
    }

    @Override
    public Response addRoleMenu(int roleId, List<Integer> menuList) {
        try {
            for (Integer menuId : menuList) {
                if("0".equals(roleMenuMapper.qryHaveMenu(roleId,menuId))){
                    roleMenuMapper.addRoleMenu(roleId,menuId);
                }
            }
            return Response.success("");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("增加角色菜单失败：{}", e.getMessage());
            return Response.error("增加角色菜单失败");
        }
    }

    @Override
    public List<AllMenuVo> getAllMenu(String flag,int roleId) {
            List<AllMenuVo> res=new ArrayList<>();
            List<Menu> menuList;
            if("1".equals(flag)){
                menuList= menuMapper.getAllMenu();
            }else{
                menuList= menuMapper.getRoleMenu(roleId);
            }
            for (Menu menu : menuList) {
                if(menu.getParentId()==0){
                    AllMenuVo allMenuVo=new AllMenuVo();
                    allMenuVo.setId(menu.getMenuId());
                    allMenuVo.setLabel(menu.getMenuName());
                    allMenuVo.setMenuSeq(menu.getMenuSeq());
                    if(StringUtils.isNotBlank(menu.getIconPath())){
                        allMenuVo.setIcon(menu.getIconPath());
                    }else{
                        allMenuVo.setIcon("");
                    }
                    res.add(allMenuVo);
                }
            }
            res= res.stream().sorted(Comparator.comparing(AllMenuVo::getMenuSeq)).collect(Collectors.toList());
            for (AllMenuVo menuVo : res) {
                for (Menu menu : menuList) {
                    if(menu.getParentId()==menuVo.getId()){
                        MenuDto menuDto=new MenuDto();
                        menuDto.setId(menu.getMenuId());
                        menuDto.setLabel(menu.getMenuName());
                        if(menuVo.getChildren()==null){
                            List<MenuDto> menuDtoList=new ArrayList<>();
                            menuDtoList.add(menuDto);
                            menuVo.setChildren(menuDtoList);
                        }else{
                            menuVo.getChildren().add(menuDto);
                        }
                    }
                }
            }
            return res;
    }

    @Override
    public List<AllRoleMenuVo> getRoleMenu(int roleId,String isRoot) {
        try {
            List<AllRoleMenuVo> res=new ArrayList<>();
            List<Menu> menuList;
            if("1".equals(isRoot)&&roleId==9){
                menuList=menuMapper.getAllMenu();
            }else{
                menuList=menuMapper.getRoleMenu(roleId);
            }
            for (Menu menu : menuList) {
                if(menu.getParentId()==0){
                    AllRoleMenuVo allRoleMenuVo =new AllRoleMenuVo();
                    allRoleMenuVo.setIcon(menu.getIconPath());
                    allRoleMenuVo.setLevel(1);
                    allRoleMenuVo.setComponent(menu.getPagePath());
                    allRoleMenuVo.setId(menu.getMenuId());
                    allRoleMenuVo.setName(menu.getMenuName());
                    allRoleMenuVo.setPath(menu.getMenuUrl());
                    allRoleMenuVo.setMenuSeq(menu.getMenuSeq());
                    res.add(allRoleMenuVo);
                }
            }
            res= res.stream().sorted(Comparator.comparing(AllRoleMenuVo::getMenuSeq)).collect(Collectors.toList());
            for (AllRoleMenuVo allroleMenuVo : res) {
                for (Menu menu : menuList) {
                    if(menu.getParentId()== allroleMenuVo.getId()){
                        RoleMenuDto roleMenuDto=new RoleMenuDto();
                        roleMenuDto.setId(menu.getMenuId());
                        roleMenuDto.setComponent(menu.getPagePath());
                        roleMenuDto.setLevel(2);
                        roleMenuDto.setName(menu.getMenuName());
                        roleMenuDto.setPath(menu.getMenuUrl());
                        if(allroleMenuVo.getChildren()==null){
                            List<RoleMenuDto> roleMenuDtoList=new ArrayList<>();
                            roleMenuDtoList.add(roleMenuDto);
                            allroleMenuVo.setChildren(roleMenuDtoList);
                        }else{
                            allroleMenuVo.getChildren().add(roleMenuDto);
                        }
                    }
                }
            }
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取角色菜单失败：{}", e.getMessage());
            return null;
        }
    }

    @Override
    public Response updateMenuIcon(String iconPath, int menuId) {
        try {
            Menu menu=menuMapper.getMenuById(menuId);
            if(menu.getParentId()!=0){
                return Response.bad("二级菜单暂不支持更新图标");
            }
            menuMapper.updateMenuById(menuId,iconPath);
            return Response.success("更新菜单图标成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("更新菜单图标失败：{}", e.getMessage());
            return Response.error("更新菜单图标失败");
        }
    }

    @Override
    public Response getAllRole() {
        try {
            List<Role> roleList=roleMapper.getAllRole();
            return Response.success(roleList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取所有角色失败：{}", e.getMessage());
            return Response.error("获取所有角色失败");
        }
    }

    @Override
    public Response getMenuByRole(int roleId) {
        try {
            List<AllMenuVo> menuList=getAllMenu("0",roleId);
            String roleName=roleMapper.getRoleNameById(roleId);
            RoleMenuVo roleMenuVo=new RoleMenuVo();
            roleMenuVo.setMenuVoList(menuList);
            roleMenuVo.setRoleName(roleName);
            return Response.success(roleMenuVo);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取角色对应的菜单失败：{}", e.getMessage());
            return Response.error("获取角色对应的菜单失败");
        }
    }
}
